import { defineComponent, reactive, ref, toRefs } from 'vue'
import { NInput, NForm, NFormItem, NModal } from 'naive-ui'
import { Response } from '@/service/modules/common/types'
import { dropTableReq } from '@/service/modules/data-manage'

const DropTableModal = defineComponent({
  name: 'DropTableModal',
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    datasourceId: {
      type: Number,
      required: true
    },
    dbName: {
      type: String,
      required: true
    },
    tableName: {
      type: String,
      required: true
    }
  },
  emits: ['modalShowChange', 'refreshList'],
  setup() {
    const state = reactive({
      form: {
        datasourceId: 0,
        dbName: '',
        tableName: '',
        reason: ''
      },
      positiveButtonDisabled: ref(false)
    })

    return {
      ...toRefs(state)
    }
  },
  methods: {
    async onPositiveClick() {
      //提交删除数据表请求
      this.positiveButtonDisabled = true
      this.form.datasourceId = this.datasourceId
      this.form.dbName = this.dbName
      this.form.tableName = this.tableName
      const res: Response<any> = await dropTableReq({
        ...this.form
      }).catch(() => {
        this.positiveButtonDisabled = false
      })
      if (res.resp_code === 0) {
        this.initData()
        this.$emit('modalShowChange', false)
        this.$emit('refreshList')
        this.positiveButtonDisabled = false
      } else {
        this.positiveButtonDisabled = false
      }
    },
    onNegativeClick() {
      this.initData()
      this.$emit('modalShowChange', false)
    },
    initData() {
      this.form.datasourceId = 0
      this.form.dbName = ''
      this.form.tableName = ''
      this.form.reason = ''
    }
  },
  render() {
    return (
      <NModal
        show={this.showModal}
        mask-closable={false}
        style='width: 400px'
        title={window.$t('dataManage.dropTable')}
        bordered={false}
        size='huge'
        preset='dialog'
        positive-text={window.$t('dialog.positiveText')}
        negative-text={window.$t('dialog.negativeText')}
        onPositiveClick={this.onPositiveClick}
        onNegativeClick={this.onNegativeClick}
        onClose={this.onNegativeClick}
      >
        <p>{window.$t('dataManage.dropTableTips') + this.tableName}</p>
        <NForm
          label-placement='top'
          require-mark-placement='right-hanging'
          label-width='auto'
        >
          <NFormItem path='reason' label={window.$t('dataManage.applyReason')}>
            <NInput
              type='textarea'
              v-model={[this.form.reason, 'value']}
              autofocus
            />
          </NFormItem>
        </NForm>
      </NModal>
    )
  }
})

export default DropTableModal
